import { udp } from '@cscec/udp-ui';
import { underscoreToCamel } from '@/utils';

// 通过请求配置获取数据
export function getRequestByConfig(
    serviceName: string, 
    cfg: {url: string, method: 'post' | 'get' | 'body', [key: string]: any}
){
  return async ({fullUrl, data, params}:{fullUrl?: string, data?: any, params?: any})=>{
    const httpRequest = udp.request as any;

    let {url: cfgUrl, method: cfgMethod, ...otherCfg} = cfg;

    if(cfgMethod == 'body'){
      otherCfg.requestType = 'json';
      cfgMethod = 'post';
    }
    if (!httpRequest[cfgMethod as any]) {
      return {
        code: 5050,
        message: `请求${cfgUrl}的配置错误，暂不支持 ${cfgMethod} 方式的请求！`, 
      };
    }
    if(otherCfg.dataType){
      otherCfg.requestType = otherCfg.dataType; // 兼容dataType
    }
    let url = fullUrl || `${serviceName}${cfgUrl.indexOf('/') === 0 ? '' : '/'}${cfgUrl}`;
    if(params){
      url = udp.handleUrl(url, params);
    }
    
    console.log('[debug] url:', url, otherCfg, data);

    const result = await httpRequest[cfgMethod as any]({ 
      url, 
      ...otherCfg,
      data 
    });
    return result;
  }
}

// 通过业务类型获取当前发布的表单信息
export async function loadDesignContent(bizCode?: string) {
  bizCode = bizCode || udp.getQueryValue('bizCode') || udp.getQueryValue('busType');
  if (!bizCode) {
    udp.alert('bizCode参数为空!');
    return {};
  }
  const billCreator = udp.getQueryValue('creator');
  const params: any = { bizCode, appFlg: 0 }; //PC端，appFlg=0
  billCreator && (params.creator = billCreator);
  const { code, message, data } = await udp.request.get({
    url: '/engine/metadata/uiExtendScheme/newGetUiSchemeInfoByBizCode',
    // url: '/engine/metadata/formModel/getFormFrontendInfo',
    data: params,
  });
  
  if (code === 0) {
    if(!data.amisUIJson){
      udp.alert('未找到对应的表单配置信息！');
      return {};
    }
    const amisUIJson = JSON.parse(data.amisUIJson);
    console.log('[debug] raw amisUIJson:', amisUIJson, JSON.parse(amisUIJson.listInfo), JSON.parse(amisUIJson.editInfo));

    const listInfo = udp.parseJson(amisUIJson.listInfo);
    _allUnderscoreToCamel(listInfo.table, bizCode, 'table');

    const editInfo = udp.parseJson(amisUIJson.editInfo);
    _allUnderscoreToCamel(editInfo.forms, bizCode, 'forms');
    _allUnderscoreToCamel(editInfo.tabs, bizCode, 'tabs');

    return data ? {
      listInfo: listInfo,
      editInfo: editInfo,
      jsInfo: amisUIJson.jsInfo,
      uiContent: udp.parseJson(data.uiContent),
      capacity: data.capacity,
      microServiceName: data.microserviceName || 'customForm',
      publicProperty: _allUnderscoreToCamel(data.publicProperty, bizCode, 'publicProperty'),
      // publicProperty: data.publicProperty,
      billNoRule: data.billNoRule || [],
      tableColPermission: data.tableColPermission || [],
      attachmentProperty: (data.attachmentPropertyList || []).reduce((p, c) => ({ ...p, [c.fieldName]: c }), {}),
    } : {};
  }
  udp.alert(message);
  return {};
}

//真坑，用户创建的表明，字段名是下划线的，但是后端页面接口(列表，info)返回的是驼峰的。uiJSON, aimisUIJson存的是原下划线的，为了统一，都转成驼峰的
function _allUnderscoreToCamel(content, bizCode, type){
  // console.log('[debug] _allUnderscoreToCamel:', JSON.parse(JSON.stringify(content)), type);

  //列表页的table
  if(type == 'table'){
    content.forEach((table)=>{
      table.id = `${bizCode}_${underscoreToCamel(table.name)}`;  
      table.name = underscoreToCamel(table.name);
      table.table = underscoreToCamel(table.table);
      table.columns.forEach((column)=>{
        column.name = underscoreToCamel(column.name);
        column.table = underscoreToCamel(column.table);
      })
    });
  //详情页的主表
  }else if(type == 'forms'){
    content.forEach((panel)=>{
      panel.body.forEach((form)=>{
        form.id = `${bizCode}_${underscoreToCamel(form.name)}`;
        form.name = underscoreToCamel(form.name);
        form.table = underscoreToCamel(form.table);
        form.body.forEach((field)=>{
          field.name = underscoreToCamel(field.name);
          field.table = underscoreToCamel(field.table);
        })
      })
    })
  //详情页的明细表
  }else if(type == 'tabs'){
    content.forEach((outerTabs)=>{
      outerTabs.tabs.forEach((innerTab)=>{
        innerTab.body.forEach((table)=>{
          if(table.type == 'table'){
            table.id = `${bizCode}_${underscoreToCamel(table.name)}`;
            table.name = underscoreToCamel(table.name);
            table.table = underscoreToCamel(table.table);
            table.columns.forEach((column)=>{
              column.name = underscoreToCamel(column.name);
            })
          }
        })
      });
    })
  //公有属性
  }else if(type == 'publicProperty'){
    content.masterTableName = underscoreToCamel(content.masterTableName);
    content.detailTableMap = Object.keys(content.detailTableMap).reduce((p, c)=>{
      p[underscoreToCamel(c)] = underscoreToCamel(content.detailTableMap[c]);
      return p;
    }, {});
  }

  // console.log('[debug] _allUnderscoreToCamel:::', content);
  return content;
}
